import axios from 'axios'
import store from '../store'
import router from '../router'

const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = store.state.token
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    console.error('API Error:', error)
    const response = error.response
    
    // 处理特定的错误状态码
    if (response?.status === 401) {
      store.commit('logout')
      router.push('/login')
      return Promise.reject('请先登录')
    }
    
    if (response?.status === 400) {
      return Promise.reject('请求参数错误')
    }
    
    // 处理后端返回的具体错误信息
    const errorMsg = response?.data?.message || 
                    response?.data?.error || 
                    error.message || 
                    '服务器错误'
    
    return Promise.reject(errorMsg)
  }
)

export default request 